陣列由小到大排序

#C#

Posted by Phyxsius on 2023-09-16


internal class Program
{
    private static void Main(string[] args)
    {
        int[] ary = { 1, 2, 7, 3, 4};

        Console.WriteLine("原始陣列內容:");
        showArray(ary);

        for (int i=0; i<ary.Length; i++)
        {
            for(int j=0; j<ary.Length; j++)
            {
                if (ary[i] < ary[j])
                {
                    swap(ary, i, j);
                }
            }
        }

        Console.WriteLine("由小到大排序後陣列內容:");
        showArray(ary);
    }

    //兩個值互相交換
    static void swap(int[] ary, int value1, int value2)
    {
        int tmp = ary[value2];
        ary[value2] = ary[value1];
        ary[value1] = tmp;
    }

    //顯示陣列內容
    static void showArray(int[] ary)
    {
        for (int i=0; i<ary.Length; i++)
        {
            Console.Write(ary[i] + ",");
        }
        Console.WriteLine();
    }
}

#C#







Related Posts

ASP.NET Core Web API 入門教學 - 自訂模型資料驗證標籤

ASP.NET Core Web API 入門教學 - 自訂模型資料驗證標籤

JS30 Day 16 筆記

JS30 Day 16 筆記

跟著 GitHub Learning Lab 實作一波

跟著 GitHub Learning Lab 實作一波


Comments